package com.example.restaurantclient.AliPay;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.load.engine.Resource;
import com.example.restaurantclient.Entities.Variable;
import com.example.restaurantclient.R;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

/**
 *  重要说明：
 *  
 *  本 Demo 只是为了方便直接向商户展示支付宝的整个支付流程，所以将加签过程直接放在客户端完成
 *  （包括 OrderInfoUtil2_0_HK 和 OrderInfoUtil2_0）。
 *
 *  在真实 App 中，私钥（如 RSA_PRIVATE 等）数据严禁放在客户端，同时加签过程务必要放在服务端完成，
 *  否则可能造成商户私密数据泄露或被盗用，造成不必要的资金损失，面临各种安全风险。
 *
 *  Warning:
 *
 *  For demonstration purpose, the assembling and signing of the request parameters are done on
 *  the client side in this demo application.
 *
 *  However, in practice, both assembling and signing must be carried out on the server side.
 */
public class PayDemoActivity extends AppCompatActivity {

	private TextView payOne;
	private TextView payThree;
	private TextView payFive;
	private TextView charge;
	private int price;
	private String prePrice;
	private ImageView close;

	/**
	 * 用于支付宝支付业务的入参 app_id。
	 */
	public static final String APPID = "2021000119626893";
	
	/**
	 * 用于支付宝账户登录授权业务的入参 pid。
	 */
	public static final String PID = "2088621957951821";

	/**
	 * 用于支付宝账户登录授权业务的入参 target_id。
	 */
	public static final String TARGET_ID = "";

	/**
	 *  pkcs8 格式的商户私钥。
	 *
	 * 	如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
	 * 	使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
	 * 	RSA2_PRIVATE。
	 *
	 * 	建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
	 * 	工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
	 */
	public static final String RSA2_PRIVATE = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDPcQcPywcCVMeGtQZ06kCUi4c9QzsCdRZukI5ZuC2L/ON5wEszeAsIIj+mpuhw2LMR7bNjo+2p4YUMFzJqslHRIX9U979jp3XXHdXGZqdQGAkxIqi/CzVnbKuy5B7BnYTnNfFPjVQKuDnNko0Xcz+W0N2RroW8+EvWxKw8WKWW8Rhtn7xtIJyED0D3dCL951Yp/dIx7OGbppdBbBylpuipwNNPrenjZy7QAbYHBa1S7bIXEVrx/aJDxKeRthhPpmbbn5ODMGC0orsplJ9hWp5w6nuhhCHLK9/oB4sedU9CBlIc7A19JNAWgxVIP75tSgnjJVb2RvXOL+93dAXIdMfPAgMBAAECggEBAL2SCiUJog8kUO6usgbYKEpXtDBtJxkYzXYfDqe5I46BfZQ/Abo4YsR9H/P5JgQyVHr24fAV19RersqczEsrSI+4b/fDLJkyaQM8VacpGo+cV5IanWFxKc2pRsOFqwG/JLxy1GKhwgLF1rUhz2R1ws/dcg53EerecdgEBW5kiHcFmC/lLTOX4Sy5p1lkc7lpU72iHRvdq7tYy4IXhhBq2FSmAoZv+5FzofeFu4+95XK/HEVOnTKOmSkqI8PqtoMvT0dhIFyFLlCzwpowEBPc1H9DL1KLtLbg32jAK8Tx8CDeRuJV6c1Xi8/YWe+VHJ4ViZgFiq2Ms7I0KKVwmwAbdwkCgYEA/AERcIll4N5W8xonYNeb2x3mK5Bye7L3UXFbo/llUcXbPGRX/sSHJdnHsWpjkzaIOdT7P1vh+cKXDdszhbmM/RF7elDDDTyCtaeZAe72eez5wXAIM0J9cgy7Px94tIHldJ/qUkZaW6cGJ9539nYbOa+wLiroWT47x14+ITTzWFsCgYEA0rsSQrRtn4yF3Hwlqfg/BSDvZTk3lPY4M1JxY6FONWfJiSL4LhymzYeKn/j8EK3EdMOfnkw5sQvCGUmR4KRky45Fho0g0H4azRb5UYqzRPZTU9FJs6n3110yDuR9pAbfbdDvpC2S3GRs0WhMBctcWI2Q/dCKPnGqbXc2drl6SJ0CgYAn9aNmTOMyvQ7cjZEg8g9st1kAH2+H3eEJsQfvAGToio8xDFhHtbIYdmgL4erYNRV01ijg6xjyGcEKGXAaDEom9ta1lojXWHkBhQnmHJZIzyLrYXBrcGej5hDq+XqSZOaVj6YAVdeOIPYA7G3pTuESTKGLMJKXVB72hiMj8NmFcQKBgQCJH2uZdjijCliMiUgk2sF/P9gnIN03FCSr2Kip8OuoOrncf6HIt6IeuWUOBYFYBQqCBE1YPzeHKiSKOeIvsClaf2BkVm8U3AnqjFl9ouhWJodAUj5IJ4B7ZkxNfob29fXrSnq1dWZL/RkGBnz5hEO555yCXHGogmQoyNrq1HRqzQKBgQDFNrnJV4c9p4cHEwau3oiT2Agfa8+D0OOgOrkKAhnH7cyI6GxjJOGB8MCMkP7MyPwxauZYDCAkYQVWYCaAeOIKcDwFwBipJBgpYQUljMJV/QdIlXEalR6JGwdTce+VKNyjNU0Ez+HfkdSOJ/zmu6lGkyqivl2ygEDb43ODCMVIFQ==";
	public static final String RSA_PRIVATE = "";
	
	private static final int SDK_PAY_FLAG = 1;
	private static final int SDK_AUTH_FLAG = 2;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@SuppressWarnings("unused")
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				@SuppressWarnings("unchecked")
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
				/**
				 * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
				 */
				String resultInfo = payResult.getResult();// 同步返回需要验证的信息
				String resultStatus = payResult.getResultStatus();
				// 判断resultStatus 为9000则代表支付成功
				if (TextUtils.equals(resultStatus, "9000")) {
					// 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
					charge.setText(price+Integer.parseInt(prePrice)+"");
					Variable.sumPrice=price+Integer.parseInt(prePrice);
					EventBus.getDefault().post("update");
//					showAlert(PayDemoActivity.this, getString(R.string.pay_success) + payResult);
                    Toast.makeText(PayDemoActivity.this, "支付成功："+payResult, Toast.LENGTH_SHORT).show();

				} else {
					// 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//					showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                    Toast.makeText(PayDemoActivity.this, "支付失败："+payResult, Toast.LENGTH_SHORT).show();
				}
				break;
			}
			case SDK_AUTH_FLAG: {
				@SuppressWarnings("unchecked")
                AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
				String resultStatus = authResult.getResultStatus();

				// 判断resultStatus 为“9000”且result_code
				// 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
				if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
					// 获取alipay_open_id，调支付时作为参数extern_token 的value
					// 传入，则支付账户为该授权账户
//					showAlert(PayDemoActivity.this, getString(R.string.auth_success) + authResult);
				} else {
					// 其他状态值则为授权失败
//					showAlert(PayDemoActivity.this, getString(R.string.auth_failed) + authResult);
				}
				break;
			}
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pay_main);
		payOne=findViewById(R.id.pay_one);
		payThree=findViewById(R.id.pay_three);
		payFive=findViewById(R.id.pay_five);
		charge=findViewById(R.id.charge);
		close=findViewById(R.id.mine_pay_back);
		prePrice=(String) charge.getText();
		payOne.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				price=100;
				prePrice=(String) charge.getText();
				Drawable myDrawable = getResources().getDrawable(R.drawable.arc_line_darkred) ;
				payOne.setBackgroundDrawable(myDrawable) ;
				payOne.setTextColor(getResources().getColor(R.color.white));
				OrderInfoUtil2_0.setFinalPrice(100+"");

				Drawable myDrawable1 = getResources().getDrawable(R.drawable.arc_line_white_black) ;
				payThree.setBackgroundDrawable(myDrawable1) ;
				payThree.setTextColor(getResources().getColor(R.color.black));

				Drawable myDrawable2 = getResources().getDrawable(R.drawable.arc_line_white_black) ;
				payFive.setBackgroundDrawable(myDrawable2) ;
				payFive.setTextColor(getResources().getColor(R.color.black));
			}
		});
		payThree.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				price=300;
				prePrice=(String) charge.getText();
				Drawable myDrawable = getResources().getDrawable(R.drawable.arc_line_darkred) ;
				payThree.setBackgroundDrawable(myDrawable) ;
				payThree.setTextColor(getResources().getColor(R.color.white));

				Drawable myDrawable1 = getResources().getDrawable(R.drawable.arc_line_white_black) ;
				payOne.setBackgroundDrawable(myDrawable1) ;
				payOne.setTextColor(getResources().getColor(R.color.black));

				Drawable myDrawable2 = getResources().getDrawable(R.drawable.arc_line_white_black) ;
				payFive.setBackgroundDrawable(myDrawable2) ;
				payFive.setTextColor(getResources().getColor(R.color.black));

				OrderInfoUtil2_0.setFinalPrice(300+"");
			}
		});
		payFive.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				price=500;
				prePrice=(String) charge.getText();
				Drawable myDrawable = getResources().getDrawable(R.drawable.arc_line_darkred) ;
				payFive.setBackgroundDrawable(myDrawable) ;
				payFive.setTextColor(getResources().getColor(R.color.white));

				Drawable myDrawable1 = getResources().getDrawable(R.drawable.arc_line_white_black) ;
				payOne.setBackgroundDrawable(myDrawable1) ;
				payOne.setTextColor(getResources().getColor(R.color.black));

				Drawable myDrawable2 = getResources().getDrawable(R.drawable.arc_line_white_black) ;
				payThree.setBackgroundDrawable(myDrawable2) ;
				payThree.setTextColor(getResources().getColor(R.color.black));
				OrderInfoUtil2_0.setFinalPrice(500+"");
			}
		});
//		close.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent();
//				//把返回数据存入Intent
//				intent.putExtra("result", "My name is linjiqin");
//				//设置返回数据
//				OtherActivity.this.setResult(RESULT_OK, intent);
//				//关闭Activity
//				OtherActivity.this.finish();
//
//			}
//		});
	}

	/**
	 * 支付宝支付业务示例
	 */
	public void payV2(View v) {
		if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
//			showAlert(this, getString(R.string.error_missing_appid_rsa_private));
			return;
		}
	
		/*
		 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
		 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
		 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险； 
		 * 
		 * orderInfo 的获取必须来自服务端；
		 */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
		Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
		String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

		String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
		String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
		final String orderInfo = orderParam + "&" + sign;
		
		final Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				PayTask alipay = new PayTask(PayDemoActivity.this);
				Map<String, String> result = alipay.payV2(orderInfo, true);
				Log.i("msp", result.toString());
				
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * 支付宝账户授权业务示例
	 */
	public void authV2(View v) {
		if (TextUtils.isEmpty(PID) || TextUtils.isEmpty(APPID)
				|| (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))
				|| TextUtils.isEmpty(TARGET_ID)) {
//			showAlert(this, getString(R.string.error_auth_missing_partner_appid_rsa_private_target_id));
			return;
		}

		/*
		 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
		 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
		 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险； 
		 * 
		 * authInfo 的获取必须来自服务端；
		 */
		boolean rsa2 = (RSA2_PRIVATE.length() > 0);
		Map<String, String> authInfoMap = OrderInfoUtil2_0.buildAuthInfoMap(PID, APPID, TARGET_ID, rsa2);
		String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);
		
		String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
		String sign = OrderInfoUtil2_0.getSign(authInfoMap, privateKey, rsa2);
		final String authInfo = info + "&" + sign;
		Runnable authRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造AuthTask 对象
				AuthTask authTask = new AuthTask(PayDemoActivity.this);
				// 调用授权接口，获取授权结果
				Map<String, String> result = authTask.authV2(authInfo, true);

				Message msg = new Message();
				msg.what = SDK_AUTH_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread authThread = new Thread(authRunnable);
		authThread.start();
	}
	
	/**
	 * 获取支付宝 SDK 版本号。
	 */
	public void showSdkVersion(View v) {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
//		showAlert(this, getString(R.string.alipay_sdk_version_is) + version);
	}



//	private static void showAlert(Context ctx, String info) {
//		showAlert(ctx, info, null);
//	}

//	private static void showAlert(Context ctx, String info, DialogInterface.OnDismissListener onDismiss) {
//		new AlertDialog.Builder(ctx)
//				.setMessage(info)
//				.setPositiveButton(R.string.confirm, null)
//				.setOnDismissListener(onDismiss)
//				.show();
//	}

	private static void showToast(Context ctx, String msg) {
		Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
	}

	private static String bundleToString(Bundle bundle) {
		if (bundle == null) {
			return "null";
		}
		final StringBuilder sb = new StringBuilder();
		for (String key: bundle.keySet()) {
			sb.append(key).append("=>").append(bundle.get(key)).append("\n");
		}
		return sb.toString();
	}

	@Override
	protected void onStart() {
		super.onStart();
		charge.setText(Variable.sumPrice+"");

	}
}
